package com.chhuang.controller;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.session.SaSessionCustomUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chhuang.annotation.CurrentUser;
import com.chhuang.bean.LoginBean;
import com.chhuang.component.I18nMessage;
import com.chhuang.constants.MConstants;
import com.chhuang.core.enums.SaCode;
import com.chhuang.core.exception.SaException;
import com.chhuang.core.bean.SaResult;
import com.chhuang.model.ChUser;
import com.chhuang.service.ChUserService;
import com.chhuang.utils.digest.Md5Util;
import com.chhuang.bean.SaUser;
import com.google.code.kaptcha.Constants;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;

/**
 * @ClassName LoginController
 * @Description 用户登录退出控制类
 * @Author Darren Huang
 * @Date 2022/12/21 22:41
 * @Version 1.0
 */
@Slf4j
@RestController
@Api(value = "用户登录", tags = "用户登录接口")
public class LoginController {

    /**
     * 获取国际化资源组件
     */
    @Resource
    private I18nMessage i18nMessage;

    @Resource
    private ChUserService chUserService;

    @PostMapping("/doLogin")
    @ApiOperation(value = "用户登录接口", notes = "用户登录接口")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "用户登录成功")
    })
    public SaResult<SaUser> login(@Validated @RequestBody LoginBean loginBean) {
        //验证校验码
        String sessionId = loginBean.getCaptchaBean().getSessionId();
        if(SaSessionCustomUtil.isExists(sessionId)) {
            SaSession saSession = SaSessionCustomUtil.getSessionById(sessionId);
            String code = (String) saSession.get(Constants.KAPTCHA_SESSION_KEY);
            if (code == null || !code.equalsIgnoreCase(loginBean.getCaptchaBean().getCaptcha())) {
                throw new SaException(SaCode.LOGIN_CAPTCHA_FAIL);
            }
        }else {
            throw new SaException(SaCode.LOGIN_CAPTCHA_FAIL);
        }
        SaSessionCustomUtil.deleteSessionById(sessionId); //删除session

        //验证登录信息
        ChUser user = chUserService.getOne(Wrappers.<ChUser>lambdaQuery().eq(ChUser::getUsername, loginBean.getAccount())
                .eq(ChUser::getPassword, Md5Util.md5(loginBean.getPassword(), loginBean.getAccount())), false);
        if(user == null){
            throw new SaException(SaCode.LOGIN_USERNAME_PASSWORD_FAIL);
        }

        //验证成功
        String clientUUID = loginBean.getClientUUID();
        if(StrUtil.isBlank(clientUUID))
            StpUtil.login(user.getUserId());//sa-token登录
        else
            StpUtil.login(user.getUserId(), clientUUID);//sa-token登录

        SaUser saUser = new SaUser();
        saUser.setToken(StpUtil.getTokenValue());//sa-token获取token
        saUser.setClientUUID(clientUUID);
        BeanUtil.copyProperties(user, saUser);
        //sa-token获取user session 并保存用户信息
        StpUtil.getSession(true).set(MConstants.SESSION_USER_KEY, saUser);

        return SaResult.data(saUser);
    }


    @GetMapping("/doLogout")
    @ApiOperation(value = "用户退出接口", notes = "用户退出接口")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "用户退出成功")
    })
    public SaResult<Void> logout(@ApiIgnore @CurrentUser SaUser saUser){
        StpUtil.logout();
        return SaResult.ok();
    }
}
